import 'package:flutter/cupertino.dart';
import 'package:macos_ui/macos_ui.dart';
import 'package:provider/provider.dart';
import '../services/app_state.dart';
import '../models/mcp_tool.dart';
import '../widgets/config_dialog.dart';
import '../widgets/tool_list.dart';
import '../widgets/parameter_form.dart';
import '../widgets/result_and_log_viewer.dart';
import '../widgets/custom_window_title_bar.dart';

/// 主屏幕
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  // 连接模式
  McpConnectionType _connectionType = McpConnectionType.sse;
  
  // HTTP/SSE模式的控制器
  final _urlController = TextEditingController();
  
  // CMD模式的控制器
  final _commandController = TextEditingController();
  final _argsController = TextEditingController();
  
  @override
  void dispose() {
    _urlController.dispose();
    _commandController.dispose();
    _argsController.dispose();
    super.dispose();
  }

  void _showConfigDialog(BuildContext context) {
    final appState = Provider.of<AppState>(context, listen: false);

    showMacosSheet(
      context: context,
      builder: (context) => ConfigDialog(initialConfig: appState.config),
    ).then((config) {
      if (config != null) {
        appState.configure(config);
      }
    });
  }
  
  void _connect(BuildContext context) async {
    final appState = Provider.of<AppState>(context, listen: false);
    
    McpConfig? config;
    
    if (_connectionType == McpConnectionType.sse) {
      if (_urlController.text.trim().isEmpty) {
        _showErrorDialog(context, 'URL不能为空');
        return;
      }
      config = McpConfig.sse(url: _urlController.text.trim());
    } else {
      if (_commandController.text.trim().isEmpty) {
        _showErrorDialog(context, '命令不能为空');
        return;
      }
      config = McpConfig.cmd(
        command: _commandController.text.trim(),
        args: _argsController.text.trim().isEmpty
            ? null
            : _argsController.text.trim().split(RegExp(r'\s+')),
      );
    }
    
    try {
      await appState.configure(config);
    } catch (e) {
      if (context.mounted) {
        _showErrorDialog(context, '连接失败: $e');
      }
    }
  }

  void _showErrorDialog(BuildContext context, String message) {
    showMacosAlertDialog(
      context: context,
      builder: (context) => MacosAlertDialog(
        appIcon: const Icon(CupertinoIcons.exclamationmark_triangle),
        title: const Text('错误'),
        message: Text(message),
        primaryButton: PushButton(
          controlSize: ControlSize.large,
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('确定'),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AppState>(
      builder: (context, appState, child) {
        // Show error dialog if there's an error
        if (appState.error != null) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _showErrorDialog(context, appState.error!);
            appState.clearError();
          });
        }

        return MacosWindow(
          child: Column(
            children: [
              // 自定义窗口标题栏
              CustomWindowTitleBar(
                title: 'MCP 工具调试器',
                actions: [
                  if (appState.isConnected) ...[
                    MacosIconButton(
                      icon: const Icon(CupertinoIcons.refresh),
                      onPressed: appState.isLoading
                          ? null
                          : () => appState.refreshTools(),
                    ),
                    const SizedBox(width: 8),
                    PushButton(
                      controlSize: ControlSize.regular,
                      secondary: true,
                      onPressed: () => appState.disconnect(),
                      child: const Text('断开连接'),
                    ),
                    const SizedBox(width: 8),
                  ],
                  PushButton(
                    controlSize: ControlSize.regular,
                    onPressed: () => _showConfigDialog(context),
                    child: const Text('高级配置'),
                  ),
                  const SizedBox(width: 8),
                ],
              ),
              
              // 连接配置区域
              Padding(
                padding: const EdgeInsets.all(12.0),
                child: Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: MacosTheme.of(context).canvasColor,
                    borderRadius: BorderRadius.circular(6),
                    border: Border.all(
                      color: MacosTheme.of(context).dividerColor,
                    ),
                  ),
                  child: Row(
                    children: [
                      // 连接类型选择
                      Row(
                        children: [
                          MacosRadioButton<McpConnectionType>(
                            value: McpConnectionType.sse,
                            groupValue: _connectionType,
                            onChanged: appState.isConnected ? null : (value) {
                              setState(() {
                                _connectionType = value!;
                              });
                            },
                          ),
                          const SizedBox(width: 6),
                          const Text('HTTP'),
                          const SizedBox(width: 16),
                          MacosRadioButton<McpConnectionType>(
                            value: McpConnectionType.cmd,
                            groupValue: _connectionType,
                            onChanged: appState.isConnected ? null : (value) {
                              setState(() {
                                _connectionType = value!;
                              });
                            },
                          ),
                          const SizedBox(width: 6),
                          const Text('CMD'),
                        ],
                      ),
                      const SizedBox(width: 16),
                      // 输入区域
                      Expanded(
                        child: _connectionType == McpConnectionType.sse
                            ? _buildHttpInput(appState)
                            : _buildCmdInput(appState),
                      ),
                      const SizedBox(width: 12),
                      // 连接按钮
                      PushButton(
                        controlSize: ControlSize.large,
                        onPressed: appState.isConnected || appState.isLoading
                            ? null
                            : () => _connect(context),
                        child: appState.isLoading
                            ? const SizedBox(
                                width: 16,
                                height: 16,
                                child: CupertinoActivityIndicator(),
                              )
                            : const Text('连接'),
                      ),
                    ],
                  ),
                ),
              ),
              
              Container(height: 1, color: MacosTheme.of(context).dividerColor),
              
              // 主内容区域
              Expanded(
                child: Row(
                  children: [
                    // 工具列表（左侧面板）
                    SizedBox(
                      width: 280,
                      child: Container(
                        decoration: BoxDecoration(
                          border: Border(
                            right: BorderSide(
                              color: MacosTheme.of(context).dividerColor,
                            ),
                          ),
                        ),
                        child: ToolList(
                          tools: appState.tools,
                          selectedTool: appState.selectedTool,
                          onToolSelected: appState.selectTool,
                          isLoading: appState.isLoading,
                        ),
                      ),
                    ),
                    // 参数表单（中间面板）
                    Expanded(
                      flex: 2,
                      child: Container(
                        decoration: BoxDecoration(
                          border: Border(
                            right: BorderSide(
                              color: MacosTheme.of(context).dividerColor,
                            ),
                          ),
                        ),
                        child: ParameterForm(
                          tool: appState.selectedTool,
                          parameters: appState.parameters,
                          onParameterChanged: (entry) {
                            appState.updateParameter(entry.key, entry.value);
                          },
                          onSubmit: () => appState.callTool(),
                          isLoading: appState.isCallingTool,  // 使用工具调用状态
                        ),
                      ),
                    ),
                    // 结果和日志查看器（右侧面板）
                    Expanded(
                      flex: 2,
                      child: ResultAndLogViewer(
                        result: appState.lastResult,
                        logs: appState.logs,
                        onClearLogs: appState.clearLogs,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
  
  Widget _buildHttpInput(AppState appState) {
    return MacosTextField(
      controller: _urlController,
      placeholder: '例如: http://127.0.0.1:18080/sse',
      enabled: !appState.isConnected,
    );
  }
  
  Widget _buildCmdInput(AppState appState) {
    return Row(
      children: [
        Expanded(
          flex: 2,
          child: MacosTextField(
            controller: _commandController,
            placeholder: '命令 (例如: npx)',
            enabled: !appState.isConnected,
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          flex: 3,
          child: MacosTextField(
            controller: _argsController,
            placeholder: '参数 (例如: @modelcontextprotocol/server-example)',
            enabled: !appState.isConnected,
          ),
        ),
      ],
    );
  }
}
